import json

from django import http
from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View
from fdfs_client.client import Fdfs_client

from areas.models import Area
from houses import utils
from houses.models import House, Facility, HouseImage
from users.models import User
from utils.login import Whetherowner
from utils.response_code import RET


class MyHomes(Whetherowner, View):
    def get(self, request):
        # if not request.user.Whetherowner:
        #     return redirect('/auth.html')

        try:
            houses = House.objects.filter(user=request.user)
        except House.DoesNotExist:
            return http.JsonResponse({'errno': RET.DBERR,
                                      'errmsg': '数据查询出错'})

        data = []
        for house in houses:
            data.append({
                'address': house.address,
                'area_name': house.area.name,
                'ctime': house.create_time,
                'house_id': house.id,
                'img_urls': house.index_image_url,
                'order_count': house.order_count,
                'price': house.price,
                'room_count': house.room_count,
                'title': house.title,
                'user_avatar': house.user.avatar_url,
            })

        return http.JsonResponse({'errno': RET.OK,
                                  'errmsg': 'ok',
                                  'data': data})


class CreateHouse(Whetherowner, View):
    def get(self, request):

        return render(request, 'newhouse.html')

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        price = json_dict.get('price')
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        deposit = json_dict.get('deposit')
        beds = json_dict.get('beds')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        facility = json_dict.get('facility')

        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, deposit, beds, min_days, max_days]):
            return http.HttpResponseForbidden('缺少必传参数')

        try:
            price = eval(price)
        except Exception:
            return http.HttpResponseForbidden('价格参数有误')

        prices = price * 100
        try:
            prices == float(price) * 100
        except Exception:
            return http.HttpResponseForbidden('价格参数有误')

        if price < 0:
            return http.HttpResponseForbidden('价格不得小于0')

        try:
            Area.objects.get(id=area_id)
        except Area.DoesNotExist:
            return http.HttpResponseForbidden('地区不存在')

        try:
            room_count = int(room_count)
        except Exception:
            return http.HttpResponseForbidden('出租房屋数目有误')

        if int(acreage) < 0:
            return http.HttpResponseForbidden('房屋面积不得小于0')

        try:
            capacity = int(capacity)
        except Exception:
            return http.HttpResponseForbidden('宜住人数有误')

        if int(capacity) <= 0:
            return http.HttpResponseForbidden('宜住人数不得小于0')

        try:
            deposit = eval(deposit)
        except Exception:
            return http.HttpResponseForbidden('押金参数有误')

        deposits = deposit * 100
        try:
            deposits == int(deposit) * 100
        except Exception:
            return http.HttpResponseForbidden('押金数额有误')

        if deposit < 0:
            return http.HttpResponseForbidden('押金数额不得小于0')

        try:
            min_days = int(min_days)
        except Exception:
            return http.HttpResponseForbidden('最少入住天数有误')

        if min_days <= 0:
            return http.HttpResponseForbidden('最少入住天数不得小于等于0')

        try:
            max_days = int(max_days)
        except Exception:
            return http.HttpResponseForbidden('最多入住天数有误')

        if max_days < 0:
            return http.HttpResponseForbidden('最多入住天数不得小于0')

        if facility:
            for i in facility:
                try:
                    Facility.objects.get(id=i)
                except Facility.DoesNotExist:
                    return http.HttpResponseForbidden('配套设施不存在')

        house = House.objects.create(
            user_id=request.user.id,
            title=title,
            price=price,
            area_id=area_id,
            address=address,
            room_count=room_count,
            acreage=acreage,
            unit=unit,
            capacity=capacity,
            deposit=deposit,
            beds=beds,
            min_days=min_days,
            max_days=max_days,
        )
        house.facilities.add(*facility)
        house.save()

        return http.JsonResponse({'errno': RET.OK,
                                  'errmsg': 'OK',
                                  'data': {'house_id': house.id}})


class HouseImages(Whetherowner, View):
    def post(self, request, house_id):
        image_url = request.FILES['house_image']
        client = Fdfs_client('lovehome/utils/fastdfs/client.conf')
        res = client.upload_by_buffer(image_url.read())
        image = res.get('Remote file_id')
        image = settings.FDFS_URL + image

        try:
            HouseImage.objects.create(house_id=house_id, url=image)
        except HouseImage.DoesNotExist:
            return http.JsonResponse({'errno': RET.DATAERR,
                                      'errmsg': '提取图片出错'})

        house = House.objects.get(id=house_id)
        if not house.index_image_url:
            house.index_image_url = image
            house.save()

        return http.JsonResponse({'errno': RET.OK,
                                  'errmsg': 'OK',
                                  'data': {'url': image}})


class HousesDetailView(View):
    def get(self,request,house_id):
        try:
            house = House.objects.get(id = house_id)
        except:
            return http.JsonResponse({'errno': 4002, 'errmsg': '该房屋不存在'})
        comments = house.order_set.all()
        comments_li = []
        for comment in comments:
            comments_li.append(
                {
                    'comment': comment.comment,
                    'ctime': comment.create_time,
                    'user_name': comment.user_name
                }
            )
        facilities = house.facilities.all()
        facilities_li = []
        for facility in facilities:
            facilities_li.append(facility.id)
        imgs = house.houseimage_set.all()
        img_urls_li = []
        for img in imgs:
            img_urls_li.append(img.url)
        house_data = {
            "acreage": house.acreage,
            "address": house.address,
            "beds": house.beds,
            "capacity": house.capacity,
            "comments":comments_li,
            "deposit": house.deposit,
            "facilities": facilities_li,
            "hid": house_id,
            "img_urls":img_urls_li,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.unit,
            "user_avatar": house.user.avatar_url,
            "user_id": house.user.id,
            "user_name": house.user.username
        }
        data = {
            'house':house_data,
            'user_id':request.user.id
        }
        result = {
            'errmsg': 'ok',
            'errno': 0,
            'data': data
        }
        return http.JsonResponse(result)


class MyhouseView(View):
    def get(self, request):

        return redirect('/static/html/myhouse.html')


class HotHousesView(View):
    def get(self, request):

        try:
            houses = House.objects.filter().order_by("-order_count")[:3]
        except:
            return http.JsonResponse({"errno": 4002, "errmsg": "数据有误"})

        hot_houses = []

        for house in houses:
            hot_houses.append({
                "house_id": house.id,
                "img_url": house.index_image_url,
                "title": house.title

            })
        return http.JsonResponse({"errno": "0", "errmsg": "OK", "data": hot_houses})

        # return render(request,"index.html",hot_houses)


class HousesSearchView(View):
    def get(self, request):

        aid = request.GET.get("aid")
        sd = request.GET.get("sd")
        ed = request.GET.get("ed")
        sk = request.GET.get("sk")
        p = request.GET.get("p", 1)

        if not all([aid, sd, ed]):
            return http.JsonResponse({"errno": 4103, "errmsg": "缺少必传参数"})
        if sk == "booking":
            sk = "-order_count"
        elif sk == "new":
            sk = "-create_time"
        elif sk == "price-inc":
            sk = "price"
        elif sk == "price-des":
            sk = "-price"
        else:
            return http.JsonResponse({"errno": 4103, "errmsg": "参数错误"})
        try:
            area_id = Area.objects.get(id=aid)
        except:
            return http.JsonResponse({"errno": 4002, "errmsg": "地区不存在"})
        days = utils.days(sd, ed)
        if not days:
            return http.JsonResponse({"errno": 4103, "errmsg": "日期输入有误"})
        houses = House.objects.filter(Q(area_id=aid, min_days__lte=days, max_days__gte=days)
                                      | Q(area_id=aid, min_days=0, max_days__gte=days)
                                      | Q(area_id=aid, min_days__lte=days, max_days=0)
                                      | Q(area_id=aid, min_days=0, max_days=0)).order_by(sk)
        paginator = Paginator(houses, 5)

        try:
            page_data = paginator.page(p)
        except:
            return http.JsonResponse({"errno": 4002, "errmsg": "无数据"})

        total_page = paginator.num_pages

        houses_list = []

        for house in page_data:
            houses_list.append({
                "area_name": house.area.name,
                "house_id": house.id,
                "order_count": house.order_count,
                "title": house.title,
                "ctime": house.create_time,
                "price": house.price,
                "address": house.address,
                "room_count": house.room_count,
                "user_avatar": house.user.avatar_url,
                "img_ur": house.index_image_url,
            })
        data = {"houses": houses_list, "total_page": total_page}

        return http.JsonResponse({"errno": 0, "errmsg": "ok", "data": data})

